package com.deep.sftp;


import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

/**
 * @author: chenly
 * @date: 2022-11-01 11:17
 * @description:
 * @version: 1.0
 */
public class SftpObjectPool implements ObjectPool<SftpClientObject> {
    private  GenericObjectPool<SftpClientObject> internalPool;

    public SftpObjectPool(SftpProperties sftpProperties) {
        this.internalPool = new GenericObjectPool<SftpClientObject>(new SftpPooledObjectFactory(sftpProperties), getPoolConfig(sftpProperties.getPool())){
            @Override
            public void returnObject(SftpClientObject sftpClient) {
                try {
                    sftpClient.getSftp().cd(sftpProperties.getRemotePath());
                } catch (Exception e) {
                }
                super.returnObject(sftpClient);
            }
        };
    }

    @Override
    public void addObject() throws Exception {
        internalPool.addObject();
    }
    @Override
    public SftpClientObject borrowObject() throws Exception {
        SftpClientObject sftpClientObject = internalPool.borrowObject();
        System.out.println("hashCode = " +  sftpClientObject.hashCode());
        return sftpClientObject;
    }
    @Override
    public void clear() {
        internalPool.clear();
    }
    @Override
    public void close() {
        internalPool.close();
    }

    @Override
    public int getNumActive() {
        return internalPool.getNumActive();
    }
    @Override
    public int getNumIdle() {
        return internalPool.getNumIdle();
    }
    @Override
    public void invalidateObject(SftpClientObject obj) throws Exception {
        internalPool.invalidateObject(obj);
    }
    @Override
    public void returnObject(SftpClientObject obj) {
        internalPool.returnObject(obj);
    }
    private GenericObjectPoolConfig<SftpClientObject> getPoolConfig(SftpProperties.Pool properties) {
        if (properties == null) {
            properties = new SftpProperties.Pool();
        }
        GenericObjectPoolConfig<SftpClientObject> config = new GenericObjectPoolConfig<>();
        config.setMinIdle(properties.getMinIdle());
        config.setMaxIdle(properties.getMaxIdle());
        config.setMaxTotal(properties.getMaxActive());
        config.setMaxWaitMillis(properties.getMaxWait());
        config.setTestOnBorrow(properties.isTestOnBorrow());
        config.setTestOnReturn(properties.isTestOnReturn());
        config.setTestWhileIdle(properties.isTestWhileIdle());
        config.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRuns());
        return config;
    }
}